/* 
 * 快速测试页面
 * 
 * 设计的快速逻辑是
 * 生产人员点击开始测试 程序一直搜索周边蓝牙设备 以列表方式展示
 * 生产人员可对列表中设备进行连接/解锁/断开/打印操作
 * 在所有环节顺畅通过的情况，最快速的完成蓝牙硬件的测试与MAC记录与条码生成工作。
 * 不考虑异常流程 不提供异常提示
 * 
 */
const PrintAPI = require('../../utils/print')
const HttpAPI = require('../../pages/http/api')
const RFBMBG22A1_service_id = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
const RFBMBG22A1_characteristic_id_write = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
const RFBMBG22A1_characteristic_id_read = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
const RFBMBG22A1_characteristic_id_at = "6E400004-B5A3-F393-E0A9-E50E24DCCA9E"
const bledata = {deviceId: "84:FD:27:EE:24:49", name: "LC0584FD27EE2449", RSSI: -55, connectable: true,testStatus:"等待测试"}
Page({
  /**
   *            数据说明
   * bleReady   蓝牙外设是否已被发现并处于可连接的状态
   * deviceId   android为蓝牙外设mac地址 ios为deviceid
   * mac        无冒号的MAC地址
   * deviceName 蓝牙外设广播时设置的name值 格式为Android LC05+mac 如LC0584FD27EE2450
   * deviceNameSet 当前扫描到的符合标准的全部蓝牙deviceName
   * soc           锁具电量 单位：mv毫伏
   * testStatusLabel 锁具测试状态
   * 
   */
  data: {
    bleReady: true,
    deviceId: "",
    devices: [],
    mac: "",
    deviceName: "",
    deviceNameSet: [],
    longitude: "113.94179",
    latitude: "35.33014",
    discloading: false,
    testStatusLabel: "准备测试",
    soc: "6688",
  },

   onShow : function () {
     //数据清零？
    this.data.deviceNameSet = new Set()
   
   },
  onHide: function () {
    //释放蓝牙 TODO要先做判断才能释放
    //wx.closeBluetoothAdapter()
    //this._discoveryStarted = false
  },
//开始测试按钮操作
startTest() {
   this.openBluetoothAdapter()
},
//结束测试按钮操作
stopTest() {
  wx.closeBluetoothAdapter()
  this._discoveryStarted = false
  this.setData({
    testStatusLabel:"测试暂停"
  })
},
//创建蓝牙连接按钮操作
createConnection(e) {
  const ds = e.currentTarget.dataset
  const deviceId = ds.deviceId
  const index = ds.index
  var that =this
  console.log('准备连接 目标设备deviceId is' + deviceId)
  wx.createBLEConnection({
    deviceId,
    success: (res) => {
      console.log('硬件连接成功 deviceId is' + deviceId)
      //把deviceid设置为当前连接的那个 显示连接成功状态
     that.data.devices[index].testStatus ="已连接"
      that.setData({
       
        devices:that.data.devices
        
      })
      //获取蓝牙服务以及对应的特征值 Android系统下可以不写 iOS必须写
      that.getBLEDeviceServices(deviceId)
    },
    fail(res) {
      console.log('连接蓝牙失败: errMsg' + res.errMsg +'连接蓝牙失败: errCode' +res.errCode)
      that.setData({
       
      })
    }
  })
},
  //向蓝牙硬件写数据 发送OPEN信息
  writeBLECharacteristicValue(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const index = ds.index
    //发送OPEN
    var lati = parseFloat(this.data.latitude).toFixed(5)
    var long = parseFloat(this.data.longitude).toFixed(5)
    var message = "OPENbluetooth00lati" + lati + "long" + long
    var that = this
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: RFBMBG22A1_service_id,
      characteristicId: RFBMBG22A1_characteristic_id_write,
      value: stringToBytes(message),
      success: function (res) {
        console.log('发送OPEN成功', res.errMsg)
        that.data.devices[index].testStatus ="已解锁"
       
        that.setData({
         
          devices:that.data.devices
        })
      },
      fail(res) {
        console.log('发送OPEN失败', res.errMsg)
       
      }
    })
  },
  //断开蓝牙连接
  closeBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const index = ds.index
    var that =this 
    wx.closeBLEConnection({
      deviceId: deviceId,
      success: (res) => {
        that.data.devices[index].testStatus ="已断开"
        this._discoveryStarted = false
        that.setData({
         
          devices:that.data.devices,
          discloading: false,

        })
        console.log('断开蓝牙成功', res.errMsg)
      },
      fail: (res) => {
       
        this.setData({
        
          discloading: false,
        })
        console.log('断开蓝牙失败', res.errMsg)
      }
    })
  },

//打印mac按钮操作
printMac(e) {
  const ds = e.currentTarget.dataset
  const index = ds.index
  const mac = ds.name
  PrintAPI.printUtil(mac)
  this.data.devices[index].testStatus ="已打印"
        this.setData({
         
          devices:this.data.devices,
         
        })
  console.log("printMac"+mac)
 
},
//向服务器上传锁具mac
uploadMac(e) {
  var that = this
  //TODO 上传MAC功能待实现
  const ds = e.currentTarget.dataset
  const index = ds.index
  const mac = ds.name
  HttpAPI.postLockMacRegister({
    mac:mac
  }).then(function (res) {
    if(res.result[0]&&res.success ==true){
      that.data.devices[index].testStatus ="已上传"
     
  }else{
    that.data.devices[index].testStatus ="上传失败"
    
  }
  that.setData({
    devices:that.data.devices,
  })
  })
},


  //初始化蓝牙模块
  openBluetoothAdapter() {
    var that = this
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log('初始化手机蓝牙成功')
        that.setData({
          
         
          bleReady: true,       
        })
       that.searchBluetooth()
      },
      fail: function (res) {
        console.log('初始化手机蓝牙失败')
        that.setData({
        
          bleReady: false,
         
        })
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            if (res.available) {
              that.setData({
              
                bleReady: true, 
              })
              that.searchBluetooth()
            }
          })
        }
      }
    })
  },


  //搜索蓝牙
  searchBluetooth() {
    var that = this
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      //allowDuplicatesKey: true,
      //通过service参数过滤掉无关蓝牙 仅仅搜索信迟达RF-BM-BG22A1相关型号
      services: [RFBMBG22A1_service_id],
      success: function (res) {
        console.log("开始搜索蓝牙设备：");
        that.setData({
          testStatusLabel: "正在测试",
          
        })
        that.onBluetoothDeviceFound()
      },
      fail: function (res) {
        that.setData({
          testStatusLabel: "蓝牙异常",
          
        })
      }
    })
  },
  //发现新的蓝牙
  onBluetoothDeviceFound() {
   
    wx.onBluetoothDeviceFound((res) => {
      console.log("onBluetoothDeviceFound");
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          console.log("!device.name");
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
           device.testStatus = "等待测试"
           device.name = device.name.slice(4)
          data[`devices[${foundDevices.length}]`] = device
          
          console.log(device)
        } else {
          device.testStatus = "等待测试"
          device.name = device.name.slice(4)
          data[`devices[${idx}]`] = device
          
        }
        //存储搜索到到devicenName到Set
        this.data.deviceNameSet.add(device.name)
        this.setData(data)
        console.log("蓝牙设备deviceId：" + device.deviceId + "蓝牙设备device name：" + device.name + "\n");
      })
    })
  },
 
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: (res) => {
        this.getBLEDeviceCharacteristics(deviceId, RFBMBG22A1_service_id)
      }
    })
  },
  //获取特征值并设置
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    var that = this
    console.log('获取蓝牙特征值')
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success(res) {
        console.warn('使能notify')
        that.openBluetoothNotify(deviceId, serviceId, RFBMBG22A1_characteristic_id_read)
      },
      fail(res) {
        console.error('获取蓝牙特征值失败', res.errMsg)
      }
    })
    // 操作之前先监听，保证第一时间获取数据 
    //TODO这个位置是仿照官方代码 但是不是很理解为什么在这个位置
    wx.onBLECharacteristicValueChange((characteristic) => {
     
      console.log("获得监听数据"+hextoString(ab2hex(characteristic.value)))
      //正则 筛选数字
      var socValue = hextoString(ab2hex(characteristic.value)).replace(/[^0-9]/ig, "")
      that.setData({
       
        soc: parseInt(socValue),
      })

    })
  },
  //使能notify
  openBluetoothNotify(deviceId, serviceId, characteristicId) {
   
    console.log("使能蓝牙特征值 openBluetoothNotify");
    wx.notifyBLECharacteristicValueChange({
      state: true,
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      success: (res) => {
        console.log('启动notify成功', res.errMsg)
       
      },
      fail: function () {
        console.log('启动notify失败');
      },
    })
  },

 

 
})

// 字符串转byte
function stringToBytes(str) {
  var array = new Uint8Array(str.length);
  for (var i = 0, l = str.length; i < l; i++) {
    array[i] = str.charCodeAt(i);
  }
  console.log(array);
  return array.buffer;
}
// ArrayBuffer转16进度字符串
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
// hex转json字符串,16进制ASCII
var hextoString = function (hex) {
  var arr = hex.split("")
  var out = ""
  for (var i = 0; i < arr.length / 2; i++) {
    var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]
    var charValue = String.fromCharCode(tmp);
    out += charValue
  }
  return out
};